package com.higold.cloud.ui.fragment

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.gyf.immersionbar.ktx.immersionBar
import com.higold.cloud.R
import com.higold.cloud.base.BaseFragment
import com.higold.cloud.mvp.contract.ReportContract
import com.higold.cloud.mvp.model.bean.postReport.PostReport
import com.higold.cloud.mvp.model.bean.UploadPic
import com.higold.cloud.mvp.model.bean.dailyPostList.DailyPostList
import com.higold.cloud.mvp.presenter.ReportPresenter
import com.higold.cloud.net.exception.ErrorStatus
import com.higold.cloud.showToast
import com.higold.cloud.ui.adapter.ReportAdapter
import com.higold.cloud.utils.AppUtils
import com.higold.cloud.utils.ImageLoader
import com.higold.cloud.utils.StatusBarUtil
import com.higold.cloud.view.CustomFullScreenPopup
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.SimpleCallback
import kotlinx.android.synthetic.main.fragment_report.*
import me.zhouzhuo.zzimagebox.ZzImageBox
import java.io.File
import java.util.*

/**
 *    author : lxz
 *    date   : 2019/6/25 10:50
 *    desc   :
 */

class ReportFragment : BaseFragment(), ReportContract.View, AMapLocationListener, BaseQuickAdapter.RequestLoadMoreListener {

    private var mTitle: String? = null

    private val mPresenter by lazy { ReportPresenter() }

    private var mLocationClient: AMapLocationClient? = null

    private var aMapLocation: AMapLocation? = null

    private lateinit var imageBoxAddMode: ZzImageBox

    private var mAdapter: ReportAdapter? = null

    private var dailyPostList: DailyPostList? = null

    private val delayMillis = 1000

    private var mCurrentCounter = 0

    private var isErr: Boolean = false

    private var mLoadMoreEndGone = false

    private var popup: CustomFullScreenPopup? = null

    private var imageUrl: String = ""

    private var isFirst: Boolean = true

    companion object {
        private val TOTAL_COUNTER = 15
        private val PAGE_SIZE = 5

        private const val CAMERA_REQUEST_CODE = 3
        val SAVED_IMAGE_PATH = Environment.getExternalStorageDirectory().absolutePath + "/photo/" + System.currentTimeMillis() + ".jpg"
        private const val IMAGE = 1
        private const val REQUEST_CROP = 4

        fun getInstance(title: String): ReportFragment {
            val fragment = ReportFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }
    }

    init {
        mPresenter.attachView(this)
    }

    override fun getLayoutId(): Int = R.layout.fragment_report

    override fun onLocationChanged(aMapLocation: AMapLocation?) {
        this.aMapLocation = aMapLocation
        mLocationClient!!.stopLocation()
        if (aMapLocation != null) {
            if (aMapLocation.errorCode == 0) {
                popup!!.findViewById<TextView>(R.id.tv_location).text = aMapLocation.address
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                showToast("定位失败")
            }
        }
    }

    override fun lazyLoad() {
        mPresenter.getDailyPostList()
    }

    override fun setDailyPostList(dailyPostList: DailyPostList) {
        multipleStatusView.showContent()
        setAdapter(dailyPostList)
    }

    override fun setUploadPic(uploadPic: UploadPic) {
        multipleStatusView.showContent()

        imageUrl = if (imageUrl == "") {
            uploadPic.data.image
        } else {
            setImageBuilder(uploadPic.data.image)
        }

        setImageBuilder(uploadPic.data.image)
        imageBoxAddMode.addImageOnlineWithRealPathAndType(uploadPic.data.image, "tag" + imageBoxAddMode.count, imageBoxAddMode.count)
    }

    private fun setImageBuilder(imageUrl: String): String {
        return this.imageUrl + "," + imageUrl
    }

    override fun setReport(report: PostReport) {
        multipleStatusView.showContent()
        showToast("提交成功")
    }

    override fun showError(errorMsg: String, errorCode: Int) {
        showToast(errorMsg)
        if (errorCode == ErrorStatus.NETWORK_ERROR) {
            multipleStatusView.showNoNetwork()
        } else {
            multipleStatusView.showError()
        }
    }

    override fun showLoading() {
        multipleStatusView.showLoading()
    }

    override fun dismissLoading() {

    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.detachView()
        mLocationClient!!.onDestroy()
    }

    override fun initView() {
        setLocationClient()

        popup = CustomFullScreenPopup(this.context!!)

        refreshLayout.setOnRefreshListener {
            mAdapter?.setEnableLoadMore(false)
            Handler().postDelayed({
                mPresenter.getDailyPostList()

                isErr = false
                mCurrentCounter = PAGE_SIZE
                mAdapter?.setEnableLoadMore(true)
            }, delayMillis.toLong())
        }

        tv_push.setOnClickListener {
            XPopup.Builder(context)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onCreated() {
                            activity?.let { it -> StatusBarUtil.darkMode(it) }
                            mLocationClient!!.startLocation()
                        }
                    })
                    .moveUpToKeyboard(false)
                    .asCustom(popup)
                    .show()
        }

        popup!!.setOnFullScreenPopupClickListener(object : CustomFullScreenPopup.FullScreenPopupClickListener {

            override fun OnImageClick(imageBoxAddMode: ZzImageBox) {
                this@ReportFragment.imageBoxAddMode = imageBoxAddMode
                PhotoChoose()
            }

            override fun okClick() {
                val params = hashMapOf("salemanId" to "1",
                        "shopName" to popup!!.findViewById<EditText>(R.id.ed_point_ad).text.toString(),
                        "hotsaleProduct" to popup!!.findViewById<EditText>(R.id.ed_hot_product).text.toString(),
                        "stockoutProduct" to popup!!.findViewById<EditText>(R.id.ed_shortage_product).text.toString(),
                        "images" to imageUrl,
                        "lat" to aMapLocation!!.latitude.toString(),
                        "lng" to aMapLocation!!.longitude.toString(),
                        "address" to aMapLocation!!.address)
                mPresenter.getReport(params)

                immersionBar {
                    statusBarColor(R.color.colorAccent)
                    titleBarMarginTop(rv_list)
                    statusBarDarkFont(false)
                    navigationBarDarkIcon(false)
                }

                popup!!.dismiss()
            }

            override fun cancelClick() {
                immersionBar {
                    statusBarColor(R.color.colorAccent)
                    titleBarMarginTop(rv_list)
                    statusBarDarkFont(false)
                    navigationBarDarkIcon(false)
                }
                popup!!.dismiss()
            }

        })
    }

    private fun setLocationClient() {
        mLocationClient = AMapLocationClient(activity!!.applicationContext)
        mLocationClient!!.setLocationListener(this)

        val option = AMapLocationClientOption()

        option.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        option.isOnceLocation = true
        option.isNeedAddress = true
        mLocationClient!!.setLocationOption(option)
    }

    private fun setAdapter(dailyPostList: DailyPostList) {
        if (refreshLayout.isRefreshing) {
            refreshLayout.finishRefresh()
            this.dailyPostList = dailyPostList

            mAdapter?.notifyDataSetChanged()
            rv_list.scheduleLayoutAnimation()
        } else {
            this.dailyPostList = dailyPostList
            rv_list.layoutManager = LinearLayoutManager(activity)

            mAdapter = ReportAdapter(this.dailyPostList!!.data)
            mAdapter?.setOnLoadMoreListener(this, rv_list)
            mAdapter?.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT)
            rv_list.adapter = mAdapter
            mCurrentCounter = mAdapter?.data!!.size
            rv_list.addOnItemTouchListener(object : OnItemClickListener() {
                override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

                }
            })

            mAdapter!!.setOnImageClickListener(object : ReportAdapter.ImageClickListener {
                override fun ImageClick(position: Int, imageView: ImageView, imageUrl: Array<String>) {
                    XPopup.Builder(context).asImageViewer(imageView, position, imageUrl.toList(), { popupView, _ ->
                        // 作用是当Pager切换了图片，需要更新源View
                        popupView.updateSrcView(imageView)
                    }, ImageLoader())
                    .show()
                }
            })
        }
    }

    override fun onLoadMoreRequested() {
        refreshLayout.isEnableRefresh = false
        if (mAdapter!!.data.size < PAGE_SIZE) {
            mAdapter!!.loadMoreEnd(true)
        } else {
            if (mCurrentCounter >= TOTAL_COUNTER) {
                mAdapter!!.loadMoreEnd(mLoadMoreEndGone)
            } else {
                if (!isErr) {
                    dailyPostList!!.data.addAll(dailyPostList!!.data)
                    mAdapter!!.notifyLoadMoreToLoading()

                    mCurrentCounter = mAdapter!!.data.size
                    mAdapter!!.loadMoreComplete()
                } else {
                    isErr = true
                    showToast("网络错误！")
                    mAdapter!!.loadMoreFail()
                }
            }
            refreshLayout.isEnableRefresh = true
        }
    }

    private fun PhotoChoose() {
//        val dialog = Dialog(activity!!.applicationContext, R.style.myDialog)
//        dialog.setContentView(R.layout.dialog_choose_photo)
//
//        dialog.findViewById<View>(R.id.tv_chose_photo).setOnClickListener {
//            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
//            startActivityForResult(intent, IMAGE)
//            dialog.dismiss()
//        }
//
//        dialog.findViewById<View>(R.id.tv_take_photo).setOnClickListener {
//            OpenCamera()
//            dialog.dismiss()
//        }
//
//        dialog.setCanceledOnTouchOutside(true)
//        dialog.show()
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, IMAGE)
    }

    private fun OpenCamera() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val file = File(SAVED_IMAGE_PATH)
        file.getParentFile().mkdirs()
        //改变Uri 注意和xml中的一致
        val uri = FileProvider.getUriForFile(activity!!.applicationContext, "com.leshang.fileprovider", file)
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        startActivityForResult(intent, CAMERA_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        //获取图片路径
        if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            val selectedImage = data.data
            mPresenter.getUploadPic(getPath(selectedImage))
        }
        if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_REQUEST_CODE) {
            AppUtils.isExist(SAVED_IMAGE_PATH)
            mPresenter.getUploadPic(SAVED_IMAGE_PATH)
        }
        if (requestCode == REQUEST_CROP && resultCode == Activity.RESULT_OK && data != null) {
            if (data.data != null) {
                val bitmap = AppUtils.decodeUriAsBitmap(activity!!.applicationContext, data.data)
                AppUtils.saveBitmap(bitmap!!, SAVED_IMAGE_PATH)
            }
            mPresenter.getUploadPic(getPath(data.data))
        }
    }

    private fun getPath(uri: Uri?): String {
        val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
        val c = activity!!.applicationContext.contentResolver.query(uri, filePathColumns, null, null, null)
        c.moveToFirst()
        val columnIndex = c.getColumnIndex(filePathColumns[0])
        val imagePath = AppUtils.compressImage(c.getString(columnIndex), SAVED_IMAGE_PATH, 30)
        AppUtils.isExist(imagePath)
        c.close()

        return imagePath
    }


}

